﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace RStudio.UIFramwork
{
    /// <summary>
    /// 处理器|关闭旧有实例
    /// </summary>
    public class HandlerUseClosePre : IUIHandler
    {
        public IUIHandler Next { get; set; }

        public void Handle(UIBase uiBase)
        {
            if (uiBase.UseClosePrevious)
            {
                var activeList = uiModuleAlive.ActiveUIDic;
                var typesToCheck = new List<Type>(activeList.Keys);

                foreach (var type in typesToCheck)
                {
                    if (activeList.TryGetValue(type, out var uiList))
                    {
                        // 筛选
                        // 排除自身
                        // 满足可关闭条件
                        var toRemove = uiList.Where(ui =>
                            ui.UID != uiBase.UID &&
                            ui.CanBeClosed
                        ).ToList();


                        foreach (var ui in toRemove)
                        {
                            // 从列表中移除
                            uiList.Remove(ui);
                            uiModuleAlive.DoDispose(ui);
                        }

                        // 如果列表已空，可选择从字典中移除该类型键（可选）
                        if (uiList.Count == 0)
                        {
                            activeList.Remove(type);
                        }
                    }
                }
            }

            Next?.Handle(uiBase);
        }




        public HandlerUseClosePre(UIModuleAlive uiModuleAlive)
        {
            this.uiModuleAlive = uiModuleAlive;
        }

        [Description("")] readonly UIModuleAlive uiModuleAlive;
    }
}
